If you wind up with an unhandled exception, its job will be cancelled.
So, in this example, the first job runs perfectly normally. The second job,
though, gets cancelled after the NullPointerException
, so it never completes
to print the "This is executed after the second delay" message.
You can learn more about this in:
Tags:
xxxxxxxxxx
1
import kotlinx.coroutines.*
2
3
fun main() {
4
val job = GlobalScope.launch(Dispatchers.Main) {
5
println("This is executed before the first delay")
6
stallForTime()
7
println("This is executed after the first delay")
8
}
9
10
GlobalScope.launch(Dispatchers.Main) {
11
println("This is executed before the second delay")
12
13
var thisIsReallyNull: String? = null
14
15
println("This will result in a NullPointerException: ${thisIsReallyNull!!.length}")
16
17
stallForTime()
18
println("This is executed after the second delay")
19
}
20
21
println("This is executed immediately")
22
}
23
24
suspend fun stallForTime() {
25
withContext(Dispatchers.Default) {
26
delay(2000L)
27
}
28
}